package com.weslide.weslideapp.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.weslide.weslideapp.R;
import com.weslide.weslideapp.component.MyLinearLayout;
import com.weslide.weslideapp.component.MyLinearLayout.OnScrollListener;

public class SlideFragment extends WeSlideFragment implements OnTouchListener,
		GestureDetector.OnGestureListener, OnItemClickListener {
	private boolean hasMeasured = false;
	private View layout_left;
	private RelativeLayout layout_middle;
	private LinearLayout layout_right;
	private ImageView iv_set;
	private ListView lv_set;

	private int MAX_WIDTH = 0;

	private final static int SPEED = 30;

	private final static int sleep_time = 5;

	private GestureDetector mGestureDetector;
	private boolean isScrolling = false;

	private float mScrollX;

	private int window_width;

	public static final String TAG = "MainFragment";

	private View view = null;
	private String title[] = { "全部", "美妆", "时尚", "教育培训", "休闲娱乐", "餐饮美食" };

	private MyLinearLayout myLayout;
	private View globalView;

	private void initView() {
		layout_left = findvViewById(R.id.layout_left);
		layout_middle = (RelativeLayout) findvViewById(R.id.layout_middle);
		layout_right = (LinearLayout) findvViewById(R.id.layout_right);
		iv_set = (ImageView) findvViewById(R.id.iv_set);
		lv_set = (ListView) findvViewById(R.id.lv_set);
		myLayout = (MyLinearLayout) findvViewById(R.id.mylaout);
		lv_set.setAdapter(new ArrayAdapter<String>(getActivity(),
				R.layout.item, R.id.tv_item, title));

		myLayout.setOnScrollListener(new OnScrollListener() {

			@Override
			public void doScroll(float distanceX) {
				doScroll(distanceX);
			}

			@Override
			public void doLoosen() {
				RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_middle
						.getLayoutParams();
				if (layoutParams.leftMargin < -window_width / 2) {
					new AsynMove().execute(-SPEED);
				} else {
					new AsynMove().execute(SPEED);
				}
			}
		});
		// 点击监听
		lv_set.setOnItemClickListener(this);

		layout_right.setOnTouchListener(this);
		layout_middle.setOnTouchListener(this);
		iv_set.setOnTouchListener(this);
		mGestureDetector = new GestureDetector(this);
		// 禁用长按监听
		mGestureDetector.setIsLongpressEnabled(false);
		getMAX_WIDTH();
	}

	private View findvViewById(int id) {
		return globalView.findViewById(id);
	}

	@Override
	public void onResume() {
		super.onResume();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		globalView = inflater.inflate(R.layout.page_slide, container, false);
		initView();
		return globalView;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_middle
				.getLayoutParams();
		// 只要没有滑动则都属于点击
		if (layoutParams.leftMargin == -MAX_WIDTH)
			Toast.makeText(getActivity(), title[position], 1).show();

	}

	@Override
	public boolean onDown(MotionEvent e) {
		int position = lv_set.pointToPosition((int) e.getX(), (int) e.getY());
		if (position != ListView.INVALID_POSITION) {
			View child = lv_set.getChildAt(position
					- lv_set.getFirstVisiblePosition());
			if (child != null) {
				child.setPressed(true);
			}
		}
		mScrollX = 0;
		isScrolling = false;
		return true;
	}

	@Override
	public void onShowPress(MotionEvent e) {

	}

	@Override
	public boolean onSingleTapUp(MotionEvent e) {

		// 点击的不是layout_left
		if (view != null && view == iv_set) {
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_middle
					.getLayoutParams();
			// 左移动
			if (layoutParams.leftMargin >= 0) {
				new AsynMove().execute(-SPEED);
				lv_set.setSelection(0);// 设置为首位.
			} else {
				// 右移动
				new AsynMove().execute(SPEED);
			}
		} else if (view != null && view == layout_middle) {
			RelativeLayout.LayoutParams layoutParams = (android.widget.RelativeLayout.LayoutParams) layout_middle
					.getLayoutParams();
			if (layoutParams.leftMargin < 0) {
				// 说明layout_left处于移动最左端状态，这个时候如果点击layout_left应该直接所以原有状态.(更人性化)
				// 右移动
				new AsynMove().execute(SPEED);
			}
		}

		return true;

	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
			float distanceY) {
		doScrolling(distanceX);
		return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {

	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		return false;
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		view = v;
		if (MotionEvent.ACTION_UP == event.getAction() && isScrolling == true) {
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_middle
					.getLayoutParams();
			if (layoutParams.leftMargin < -window_width / 2) {
				new AsynMove().execute(-SPEED);
			} else {
				new AsynMove().execute(SPEED);
			}
		}
		return mGestureDetector.onTouchEvent(event);
	}

	/***
	 * 获取移动距离 移动的距离其实就是layout_left的宽度
	 */
	void getMAX_WIDTH() {
		ViewTreeObserver viewTreeObserver = layout_middle.getViewTreeObserver();
		// 获取控件宽度
		viewTreeObserver.addOnPreDrawListener(new OnPreDrawListener() {
			@Override
			public boolean onPreDraw() {
				if (!hasMeasured) {
					window_width = getActivity().getWindowManager()
							.getDefaultDisplay().getWidth();
					MAX_WIDTH = layout_right.getWidth();
					RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_middle
							.getLayoutParams();
					RelativeLayout.LayoutParams layoutParams_1 = (RelativeLayout.LayoutParams) layout_right
							.getLayoutParams();
					ViewGroup.LayoutParams layoutParams_2 = myLayout
							.getLayoutParams();
					// 注意： 设置layout_left的宽度。防止被在移动的时候控件被挤压
					layoutParams.width = window_width;
					layout_middle.setLayoutParams(layoutParams);

					// 设置layout_right的初始位置.
					layoutParams_1.leftMargin = window_width;
					layout_right.setLayoutParams(layoutParams_1);
					// 注意：设置lv_set的宽度防止被在移动的时候控件被挤压
					layoutParams_2.width = MAX_WIDTH;
					myLayout.setLayoutParams(layoutParams_2);

					Log.v(TAG, "MAX_WIDTH=" + MAX_WIDTH + "width="
							+ window_width);
					hasMeasured = true;
				}
				return true;
			}
		});

	}

	/***
	 * listview 正在滑动时执行.
	 */
	void doScrolling(float distanceX) {
		// distanceX=-distanceX;
		isScrolling = true;
		mScrollX += distanceX;// distanceX:向左为正，右为负
		RelativeLayout.LayoutParams layoutLeftParams = (RelativeLayout.LayoutParams) layout_left
				.getLayoutParams();
		RelativeLayout.LayoutParams layoutMiddleParams = (RelativeLayout.LayoutParams) layout_middle
				.getLayoutParams();
		RelativeLayout.LayoutParams layoutRightParams = (RelativeLayout.LayoutParams) layout_right
				.getLayoutParams();
		layoutMiddleParams.leftMargin -= mScrollX;
		layoutRightParams.leftMargin = window_width
				+ layoutMiddleParams.leftMargin;
		if (layoutMiddleParams.leftMargin >= 0) {
			isScrolling = false;// 拖过头了不需要再执行AsynMove了
			layoutMiddleParams.leftMargin = 0;
			layoutRightParams.leftMargin = window_width;

		} else if (layoutMiddleParams.leftMargin <= -MAX_WIDTH) {
			// 拖过头了不需要再执行AsynMove了
			isScrolling = false;
			layoutMiddleParams.leftMargin = -MAX_WIDTH;
			layoutRightParams.leftMargin = window_width - MAX_WIDTH;
		}
		Log.v(TAG, "layoutParams.leftMargin=" + layoutMiddleParams.leftMargin
				+ ",layoutParams_1.leftMargin =" + layoutRightParams.leftMargin);

		layout_middle.setLayoutParams(layoutMiddleParams);
		layout_right.setLayoutParams(layoutRightParams);
	}

	class AsynMove extends AsyncTask<Integer, Integer, Void> {

		@Override
		protected Void doInBackground(Integer... params) {
			int times = 0;
			if (MAX_WIDTH % Math.abs(params[0]) == 0)// 整除
				times = MAX_WIDTH / Math.abs(params[0]);
			else
				times = MAX_WIDTH / Math.abs(params[0]) + 1;// 有余数

			for (int i = 0; i < times; i++) {
				publishProgress(params[0]);
				try {
					Thread.sleep(sleep_time);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

			return null;
		}

		/**
		 * update UI
		 */
		@Override
		protected void onProgressUpdate(Integer... values) {
			RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_middle
					.getLayoutParams();
			RelativeLayout.LayoutParams layoutParams_1 = (RelativeLayout.LayoutParams) layout_right
					.getLayoutParams();
			// 右移动
			// values[0]=-values[0];
			if (values[0] > 0) {
				layoutParams.leftMargin = Math.min(layoutParams.leftMargin
						+ values[0], 0);
				layoutParams_1.leftMargin = Math.min(layoutParams_1.leftMargin
						+ values[0], window_width);
				Log.v(TAG, "layout_left右" + layoutParams.leftMargin
						+ ",layout_right右" + layoutParams_1.leftMargin);
			} else {
				// 左移动
				layoutParams.leftMargin = Math.max(layoutParams.leftMargin
						+ values[0], -MAX_WIDTH);
				layoutParams_1.leftMargin = Math.max(layoutParams_1.leftMargin
						+ values[0], window_width - MAX_WIDTH);
				Log.v(TAG, "layout_left左" + layoutParams.leftMargin
						+ ",layout_right左" + layoutParams_1.leftMargin);
			}
			layout_right.setLayoutParams(layoutParams_1);
			layout_middle.setLayoutParams(layoutParams);

		}

	}

	@Override
	public void onStop() {
		super.onStop();
	}
}
